package com.longrise.bjjt.util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

public class StringUtils {

    private final static Pattern emailer = Pattern
            .compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))" +
                    "([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
    private final static Pattern phone = Pattern.compile("^[1][0-9]{10}$"); // 用户名6-15字母的正则
    private final static Pattern Account = Pattern
            .compile("^[0-9A-Za-z]{6,12}$");// ^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,15}$
    // 密码的正则
    private final static Pattern Password = Pattern
            .compile("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$");

    // 车牌正则 [\u4e00-\u9fa5]{1}[A-Z]{1}[A-Z_0-9]{5}
    // /^[\u4e00-\u9fa5]{1}[A-Z]{1}[A-Z_0-9]{5}$/;
    private final static Pattern Carnum = Pattern
            .compile("^[\u4e00-\u9fa5]{1}[A-Z]{1}[A-Z_0-9]{5}$");

    // 车架VIN正则
    private final static Pattern Carvin = Pattern.compile("^[a-zA-Z0-9]{17}$");
    // 发动机号
    private final static Pattern Carenginenumber = Pattern
            .compile("^[a-zA-Z0-9]{8}$");

    public final static String UTF_8 = "utf-8";

    /**
     * 判断字符串是否有值，如果为null或者是空字符串或者只有空格或者为"null"字符串，则返回true，否则则返回false
     */
    public static boolean isEmpty(String value) {
        if (value != null && !"".equalsIgnoreCase(value.trim())
                && !"null".equalsIgnoreCase(value.trim())) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 判断多个字符串是否相等，如果其中有一个为空字符串或者null，则返回false，只有全相等才返回true
     */
    public static boolean isEquals(String... agrs) {
        String last = null;
        for (int i = 0; i < agrs.length; i++) {
            String str = agrs[i];
            if (isEmpty(str)) {
                return false;
            }
            if (last != null && !str.equalsIgnoreCase(last)) {
                return false;
            }
            last = str;
        }
        return true;
    }

    /**
     * 判断是不是一个合法的手机号码
     */
    public static boolean isPhone(CharSequence phoneNum) {
        if (isEmpty(phoneNum))
            return false;
        return phone.matcher(phoneNum).matches();
    }

    /**
     * 判断给定字符串是否空白串 空白串是指由空格、制表符、回车符、换行符组成的字符串 若输入字符串为null或空字符串，返回true
     */
    public static boolean isEmpty(CharSequence input) {
        if (input == null || "".equals(input))
            return true;

        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
                return false;
            }
        }
        return true;
    }

    /**
     * 判断是不是一个合法的用户名
     */
    public static boolean isMathAccount(CharSequence account) {
        if (isEmpty(account))
            return false;
        return Account.matcher(account).matches();
    }

    public static boolean isPassword(CharSequence password) {
        if (isEmpty(password))
            return false;
        return Password.matcher(password).matches();
    }

    public static boolean isCar(CharSequence carnum) {
        if (isEmpty(carnum))
            return false;
        return Carnum.matcher(carnum).matches()
                || Carvin.matcher(carnum).matches()
                || Carenginenumber.matcher(carnum).matches();
    }

    /**
     * 图像常用压缩 正常情况下我们应该把两者相结合的，所以有了下面的算法（在项目中直接用，清晰度在手机上没问题）
     */
    public static File scal(String path) {
        File outputFile = new File(path);
        long fileSize = outputFile.length();
        final long fileMaxSize = 150 * 1024;
        if (fileSize >= fileMaxSize) {
            try {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(path, options);
                int height = options.outHeight;
                int width = options.outWidth;
                double scale = Math.sqrt((float) fileSize / fileMaxSize);
                options.outHeight = (int) (height / scale);
                options.outWidth = (int) (width / scale);
                options.inSampleSize = (int) (scale + 0.5);
                options.inJustDecodeBounds = false;
                Bitmap bitmap = BitmapFactory.decodeFile(path, options);
                outputFile = new File(StringUtils.createImageFile().getPath());
                FileOutputStream fos = null;
                fos = new FileOutputStream(outputFile);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fos);
                fos.close();
                if (!bitmap.isRecycled()) {
                    bitmap.recycle();
                } else {
                    File tempFile = outputFile;
                    outputFile = new File(StringUtils.createImageFile().getPath());
                    StringUtils.copyFileUsingFileChannels(tempFile, outputFile);
                }

            } catch (Exception e) {

                e.printStackTrace();
                return null;
            }

        }
        return outputFile;
    }

    public static Uri createImageFile() {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp;
        File storageDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES);
        File image = null;
        try {
            image = File.createTempFile(imageFileName, ".jpg", storageDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // Save a file: path for use with ACTION_VIEW intents
        return Uri.fromFile(image);
    }

    public static void copyFileUsingFileChannels(File source, File dest) {
        FileChannel inputChannel = null;
        FileChannel outputChannel = null;
        try {
            try {
                inputChannel = new FileInputStream(source).getChannel();
                outputChannel = new FileOutputStream(dest).getChannel();
                outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
            } catch (IOException e) {

                e.printStackTrace();
            }
        } finally {
            try {
                inputChannel.close();
                outputChannel.close();
            } catch (IOException e) {

                e.printStackTrace();
            }
        }
    }
}
